import warnings
warnings.filterwarnings("ignore")
import pandas as pd
import numpy as np
#自己预留的代码
from timeit import default_timer as timer
import time
from accuracy import RMSE,MAE,MAPE,R_square
from read_data import *
from ALO_NEW import *
from model import *
import warnings
warnings.filterwarnings("ignore")
# In[158]:
def run_alo_lstm(city,mod,sequence_length,horizon,decomposition):
    times = time.strftime('%Y-%m-%d-%H-%M-%S',time.localtime(time.time()))
    filename = str(times)+'_' + "h"+str(horizon)+"_"+mod+ ".csv"
    figname = str(times)+'_' +"h"+str(horizon)+"_"+mod+".png"
    savepath = save_path+city+"/"+mod+ "/" 
    generpath(savepath)
    datapath = data_path +'data'+"_"+ decomposition + ".csv"

    if  decomposition in mod:
     #   "IMF1","IMF2","IMF3","IMF4","IMF5","IMF6","IMF7","IMF8","IMF9","IMF10"
        # a = ["IMF4"]
        # a = ["IMF1","IMF2","IMF3","IMF4","IMF5","IMF6","IMF7","IMF8","IMF9","IMF10","IMF11"]
        a=['imf0','imf1','imf2','imf3','imf4','imf5','imf6','imf7']
        for i in a:
            saveindex = i
            index = i
            horizon = horizon
            
            def function(variables_values =[1,1,2]):
                sequence_length = int(variables_values[2])
                x_train_initial,x_test_initial,y_train_initial,y_test_initial,x_train,x_test,y_train,y_test = read_data(datapath,index,sequence_length,horizon)
                model = Sequential()
                model.add(LSTM(int(variables_values[0]),input_shape=(x_train.shape[1],1),return_sequences=True))
                model.add(LSTM(int(variables_values[1])))
                model.add(Dense(1))
                model.compile(loss='mean_squared_error',optimizer='adam')
                model.fit(x_train,y_train,epochs=epochs,verbose = 0)
 
                result = model.predict(x_test)
                y_test_rel,y_test_pre = iverse_data(y_train_initial,result,y_test)
                
                fitness = R_square(y_test_rel,y_test_pre)

                return fitness
            alo = ant_lion_optimizer(colony_size = 3,
                         min_values = [1,1,12],max_values = [30,50,12],
                         iterations = 5, target_function = function)
            sequence_length = int(alo[2])
            alo = alo[:2]
            x_train_initial,x_test_initial,y_train_initial,y_test_initial,x_train,x_test,y_train,y_test = read_data(datapath,index,sequence_length,horizon)
            # print("x_train", x_train.shape)
            # print("y_train", y_train.shape)
            # print("x_test", x_test.shape)
            # print("y_test", y_test.shape)
            model = alo_LSTM_model(x_train,y_train,sequence_length,alo,35,verbose)
            pre = model.predict(x_test)
            y_test_rel,y_test_pre = iverse_data(y_train_initial,pre,y_test)
        
            print("----------",i,"----------")
            print('MAE：',MAE(y_test_rel,y_test_pre))
            print('RMSE：',RMSE(y_test_rel,y_test_pre))
            print('MAPE：',MAPE(y_test_rel,y_test_pre)[0])
            print('R方：',R_square(y_test_rel,y_test_pre))
            generfile(savepath,filename,len(y_test))
            datasave(savepath+filename,saveindex,y_test_pre)
            print("----------",index,"had finished","----------")
# In[]
        savepath1 = savepath+filename
        figpath = savepath +str(times)+"_"+mod+".png"
        datapr = pd.read_csv(savepath1)
        datapr1 = np.array(datapr)[:,2:]
        y_pre = np.sum(datapr1,axis=1)
        y_pre = y_pre.reshape(-1,1)
        datare = pd.read_csv(data_path+origin_data)
        datare.fillna(method='pad', inplace=True)
        y_rel = np.array(datare[city][-len(y_pre):]).reshape(-1,1)
        y_pre = np.array(y_pre).reshape(len(y_pre),)
        y_rel = np.array(y_rel).reshape(len(y_pre),)
        
        generfile(savepath,str(times)+'_' +"合并结果.csv",len(y_test))
        datasave(savepath+str(times)+'_' +"合并结果.csv",mod+"_h"+str(horizon),y_pre)
        
        preplot(y_pre,y_rel,figpath)
        
        alo_lstm_mae = MAE(y_rel,y_pre)
        alo_lstm_rmse = RMSE(y_rel,y_pre)
        alo_lstm_mape = MAPE(y_rel,y_pre)
        alo_lstm_R = R_square(y_rel,y_pre)
        
        alo_lstm_zb = [alo_lstm_mae,alo_lstm_rmse,alo_lstm_mape,alo_lstm_R]
        alo_lstm_zb = np.array(alo_lstm_zb).reshape(-1,1)
        zbfile = str(times)+"_指标" + ".csv"
        generfile(savepath,zbfile,len(alo_lstm_zb))
        datasave(savepath+zbfile,"pso_lstm",alo_lstm_zb)

        print(city,mod,horizon)
        print('MAE：',alo_lstm_mae)
        print('RMSE：',alo_lstm_rmse)
        print('MAPE：',alo_lstm_mape)
        print('R方：',alo_lstm_R)
 # In[153]:
data_path = ""
save_path = "预测/"
origin_data = "data.csv"
decomp_index = ['EEMD1']
n_multi = 0
verbose = 0
sequence_length = 8
netmodel = "HHO_LSTM"
decomposition = decomp_index[0]
mod = netmodel +'_' + decomposition
cityindx = ["Power"]
epochs_index = [27]
hindex = [1]
#"""
# In[153]:
for city in cityindx:
    for h in hindex:
        for epo in epochs_index:
            epochs = epo
            horizon = h
            city = city
            print("----------",city,mod,"h:",horizon,"epochs:",epochs,"----------")
            run_alo_lstm(city,mod,sequence_length,horizon,decomposition)

#"""